//
//  ShopCartViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/23.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ShopCartProductCell.h"
#import "ProductDetailViewController.h"

#import "SubmitOrderViewController.h"

#import "ShopCartViewController.h"

@interface ShopCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;


@property (nonatomic, strong)NSMutableArray <CommonShopCartModel *>*dataArray;

//优惠信息
@property (weak, nonatomic) IBOutlet UILabel *discountLab;

//合计
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;

@property (weak, nonatomic) IBOutlet UIButton *handleBtn;


@property (weak, nonatomic) IBOutlet UIButton *selectAllBtn;

@property (nonatomic, assign) BOOL isAllSel;


@property (weak, nonatomic) IBOutlet UILabel *totalLab;



@end

@implementation ShopCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self request_cart];
}



- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:self.handleBtn.frame.size.height/2];
    });
}

- (void)initView {
    
    self.title = @"购物车";
    self.isAllSel = NO;
    [self.selectAllBtn setImage:[UIImage imageNamed:self.isAllSel?@"common_sel":@"common_nor"] forState:UIControlStateNormal];

    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableview.showsHorizontalScrollIndicator = NO;
    _tableview.showsVerticalScrollIndicator = NO;
    
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    _tableview.estimatedRowHeight = 0;
    
    _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
    _tableview.showsVerticalScrollIndicator = NO;
    [_tableview registerNib:[UINib nibWithNibName:@"ShopCartProductCell" bundle:nil] forCellReuseIdentifier:@"ShopCartProductCellID"];
    
}

- (IBAction)selectAllAction:(id)sender {
    
    [self changeAllStatus];
}

- (IBAction)handleAction:(id)sender {
    
    NSMutableArray <CommonShopCartModel *>*dataArray = @[].mutableCopy;
    for (CommonShopCartModel *model in self.dataArray) {
        if (model.isSel) {
            [dataArray addObject:model];
        }
    }
    
    if (dataArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择婚品后再结算"];
        [SVProgressHUD dismissWithDelay:2];
        return;
    }
    
    SubmitOrderViewController *vc = [[SubmitOrderViewController alloc] init];
    vc.dataArray = dataArray;
    [self.navigationController pushViewController:vc animated:YES];
}

//选择cell选中的时候调用
- (void)refreshSelAllBtnStatus {
    
    NSInteger selCount = 0;
    for (CommonShopCartModel *model in self.dataArray) {
        if (model.isSel) {
            selCount++;
        }
    }
    if (selCount == self.dataArray.count) {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"common_sel"] forState:UIControlStateNormal];
        self.isAllSel = YES;
    } else {
        [self.selectAllBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
        self.isAllSel = NO;
    }
}

- (void)changeAllStatus {
    
    self.isAllSel = !self.isAllSel;
    [self.selectAllBtn setImage:[UIImage imageNamed:self.isAllSel?@"common_sel":@"common_nor"] forState:UIControlStateNormal];

    for (CommonShopCartModel *model in self.dataArray) {
        model.isSel = self.isAllSel;
    }
    
    [self.tableview reloadData];
    [self calculatePrice];
}


- (void)calculatePrice {
    NSInteger count = 0;
    double totalMoney = 0;

    for (int i = 0; i < self.dataArray.count; i++) {
        CommonShopCartModel *model = self.dataArray[i];
        
        if (model.isSel) {
            count = count + model.goodsNum;
            totalMoney = totalMoney + (model.sellerGoodsSpecs.specPrice * model.goodsNum);
        }
    }
    
    [self.handleBtn setTitle:[NSString stringWithFormat:@"结算(%ld)",count] forState:UIControlStateNormal];
    self.totalLab.text = [NSString stringWithFormat:@"合计:¥%@",[Utilities changeDoubleToString:totalMoney]];
}

#pragma mark UITableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
    vc.goodsId = self.dataArray[indexPath.row].goodsId;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColorHex(0xf0f0f0);
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShopCartProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopCartProductCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.textFieldShouldEndEditingBlock = ^(UITextField * _Nonnull textField) {
      
        weakSelf.dataArray[indexPath.row].goodsNum = textField.text.integerValue;
        [weakSelf.tableview reloadData];
    };
    
    cell.ShopCartProductCellBlock = ^(ShopCartProductCellType type) {
      
        switch (type) {
                
            case ShopCartProductCellType_sel:{
                
                weakSelf.dataArray[indexPath.row].isSel = !weakSelf.dataArray[indexPath.row].isSel;
                [weakSelf refreshSelAllBtnStatus];

            } break;
            case ShopCartProductCellType_cut:{
                
                if (weakSelf.dataArray[indexPath.row].goodsNum > 1) {
                    weakSelf.dataArray[indexPath.row].goodsNum--;

                } else {
                    [SVProgressHUD showErrorWithStatus:@"购物车数量最小为1"];
                    [SVProgressHUD dismissWithDelay:1];
                }
                
            } break;
            case ShopCartProductCellType_add:{
                
                weakSelf.dataArray[indexPath.row].goodsNum++;

            } break;
            default:
                break;
        }
        [self calculatePrice];
        [weakSelf.tableview reloadData];

    };
    
    return cell;
}


#pragma mark 左滑删除
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

    }
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull deleteIndexPath) {

        [weakSelf request_deleteCartWithIndex:indexPath.row];
    }];

    deleteRowAction.backgroundColor = UIColorHex(0xFF2442);
    
    UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"移入收藏" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull deleteIndexPath) {

        [weakSelf request_collectWithIndex:indexPath.row];
    }];

    collectRowAction.backgroundColor = UIColorHex(0xFF942B);
    
    
    return @[deleteRowAction,collectRowAction];
}

- (NSMutableArray<CommonShopCartModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_cart {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_ShopCart];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [t setValue:self.storeId forKey:@"sellerId"];
    [dic setValue:t forKey:@"t"];
    [dic setValue:@(1) forKey:@"pageNum"];
    [dic setValue:@(1000) forKey:@"pageSize"];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                        
                if ([list isKindOfClass:[NSArray class]]) {
                    weakSelf.dataArray = @[].mutableCopy;
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonShopCartModel *model = [CommonShopCartModel modelWithDictionary:list[i]];

                            NSDictionary *seller = [listDic valueForKey:@"seller"];
                            NSDictionary *sellerGoods = [listDic valueForKey:@"sellerGoods"];
                            NSDictionary *sellerGoodsSpecs = [listDic valueForKey:@"sellerGoodsSpecs"];
                            
                            model.sellerModel = [CommonSellerModule modelWithDictionary:seller];
                            model.sellerGoodsModel = [CommonPackageModel modelWithJSON:sellerGoods];
                            model.sellerGoodsSpecs = [CommonSkuModel modelWithDictionary:sellerGoodsSpecs];
                            model.isSel = NO;
                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    
                    if (weakSelf.dataArray.count == 0) {
                        if (weakSelf.tableview) {
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoCart btnTitle:@"" didPressButton:^{}];
                        }
                    }
                    [weakSelf.tableview reloadData];
                }
            }
        }

        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (void)request_deleteCartWithIndex:(NSInteger)index {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.dataArray[index].uscId forKey:@"uscId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_DeleteCart];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在删除"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [weakSelf request_cart];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

- (void)request_collectWithIndex:(NSInteger)index {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    [dic setValue:self.dataArray[index].goodsId forKey:@"baseId"];
    [dic setValue:@(4) forKey:@"collectType"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_AddCollect];
    
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            } else {
               [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
               [SVProgressHUD dismissWithDelay:1];
           }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}

@end
